import time
import requests


class Stock:
    """
    股票对象，创建的时候自动获得价格，可以比较是否相等
    """
    def __init__(self, stock_code, stock_name=None):
        self.code = stock_code if stock_code.startswith('s') else add_stock_type(stock_code)
        self.name = stock_name
        # self.now_pri = None
        # self.pri = self._get_nowpri() if pri is None else pri

    def __eq__(self, other):
        if self.code == other.code:
            return True
        else:
            return False

    def __str__(self):
        return '股票代码 {}'.format(self.code)

    @property
    def code_without_prefix(self):
        return self.code[2:]

    @property
    def pri(self):
        # TODO: 买入的时候要现在的价格，而不是预警价格
        return self._get_nowpri()

    def _get_nowpri(self):
        """
        获得股票现在的价格
        :param stock_code: 股票ID，包含英文前缀
        :return:股票的价格(float)
        """

        def jvhe(stock_code):
            url = "http://web.juhe.cn:8080/finance/stock/hs"
            params = {"key": "9f1caeead1e96e6b3c00c740b7426455", "gid": stock_code}
            response = requests.request("GET", url, params=params)
            print(response.json())
            print(stock_code)
            data = response.json()['result'][0]['data']
            return data['nowPri']

        def xinlang(stock_code):
            value_num = 3
            # print("http://hq.sinajs.cn/list=%s" % (stock_code,))
            response = requests.get("http://hq.sinajs.cn/list=%s" % (stock_code,))
            try:
                result = response.text.split(',')[value_num]
                return result
            except(IndexError):
                print('新浪股票API发生了未知情况，具体response如下\n', response.text)
                print(stock_code)
                return 0

        result = xinlang(self.code)
        if result == 0:
            result = jvhe(self.code)
        return float(result)


def add_stock_type(stock_code):
    """
    增加股票代码的前缀，判断股票ID对应的证券市场
    匹配规则
    ['50', '51', '60', '90', '110'] 为 sh
    ['00', '13', '18', '15', '16', '18', '20', '30', '39', '115'] 为 sz
    ['5', '6', '9'] 开头的为 sh， 其余为 sz
    :param stock_code:股票ID, 若以 'sz', 'sh' 开头直接返回对应类型，否则使用内置规则判断
    :return 'sh' or 'sz'"""
    assert type(stock_code) is str, "stock code need str type"
    if stock_code.startswith(("sh", "sz")):
        return stock_code
    if stock_code.startswith(
            ("50", "51", "60", "90", "110", "113", "132", "204")
    ):
        return "sh" + stock_code
    if stock_code.startswith(
            ("00", "13", "18", "15", "16", "18", "20", "30", "39", "115", "1318")
    ):
        return "sz" + stock_code
    if stock_code.startswith(("5", "6", "9", "7")):
        return "sh" + stock_code
    return "sz" + stock_code


if __name__ == '__main__':
    # time_list = list()
    # for i in range(1000):
    #     start = time.time()
    #     st = Stock('603015')
    #     end = time.time()
    #
    #     run_time = end-start
    #     print(st, '运行时间', run_time)
    #     time_list.append(run_time)
    #
    # time_list.sort()
    # print('平均耗时', sum(time_list)/len(time_list))
    # print('最大耗时')
    # for i in time_list[:-11:-1]:
    #     print(round(i, 2))
    st = Stock('603015')
    print(st.code_without_prefix)